package com.education.service.system;

import com.education.common.utils.MapTreeUtils;
import com.education.common.utils.ObjectUtils;
import com.education.common.utils.Result;
import com.education.common.utils.ResultCode;
import com.education.mapper.system.SystemMenuMapper;
import com.education.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 余一
 * @Description
 * @date 2021/7/10 14:50
 */
@Service
public class SystemMenuService extends BaseService<SystemMenuMapper> {

    @Autowired
    private SystemRoleMenuService systemRoleMenuService;

    public List<Map> queryList(Map params){
        return mapper.queryList(params);
    }


    public Result findById(Integer id) {
        Map menuMap = mapper.findById(id);
        List<Map> menus = mapper.queryList(new HashMap());
        List<Map> parentList = MapTreeUtils.getParentList(menus, (Integer) menuMap.get("parent_id"));
        List<Integer> parentIds = parentList.stream()
                .map(item -> (Integer) item.get("id"))
                .collect(Collectors.toList());
        menuMap.put("parentIds",parentIds);
        return Result.success(menuMap);
    }

    @Override
    public Result deleteById(Map modelMap) {
        List<Map> menus = mapper.queryList(new HashMap());
        List<Map> childrenTree = MapTreeUtils.getChildrenTree(menus, (Integer) modelMap.get("id"));
        if (childrenTree.isEmpty())
            return super.deleteById(modelMap);
        return Result.fail(ResultCode.FAIL,"请先删除子菜单");
    }

    public List<Integer> getRolePermission(Integer roleId) {
        List<Integer> roleIds = new ArrayList<>();
        roleIds.add(roleId);
        Map params = new HashMap();
        params.put("roleIds",roleIds);
        List<Map> menuList = systemRoleMenuService.findMenuListByRoleIds(params);
        List<Integer> menuIds = new ArrayList<>();
        // 找出最后一级的子菜单集合
        if (ObjectUtils.isNotEmpty(menuList)) {
            menuList.forEach(menu -> {
                Integer menuId = (Integer) menu.get("id");
                Integer parentId = (Integer) menu.get("parent_id");
                if (parentId != ResultCode.FAIL){
                    List<Map> childrenList = MapTreeUtils.getChildrenTree(menuList, menuId);
                    if (ObjectUtils.isEmpty(childrenList)){
                        menuIds.add(menuId);
                    }
                }
            });
        }
        return menuIds;
    }
}
